#include "controller_base.hpp"

#include "dialogs.hpp"
#include "display.hpp"
#include "foreach.hpp"
#include "game_preferences.hpp"
#include "log.hpp"
#include "mouse_handler_base.hpp"

static lg::log_domain log_display("display");
#define ERR_DP LOG_STREAM(err, log_display)

controller_base::controller_base(
	int ticks, const config& game_config, CVideo&) :
	game_config_(game_config),
	ticks_(ticks),
	key_(),
	browse_(false),
	scrolling_(false)
{
}

controller_base::~controller_base()
{
}

int controller_base::get_ticks()
{
	return ticks_;
}

void controller_base::handle_event(const SDL_Event& event)
{
	if (gui::in_dialog())
	{
		return;
	}
	
	switch(event.type)
	{
		case SDK_KEYDOWN:
			if (have_keyboard_focus())
			{
				process_keydown_event(event);
				hotkey::key_event(get_display(), event.key, this);
			}
			else
			{
				process_focus_keydown_event(event);
				break;
			}
		case SDL_KEYUP:
			process_keyup_event(event);
			break;
		case SDL_MOUSEMOTION:
			SDL_Event new_event;
			if (SDL_PeepEvents(&new_event, 1, SDL_GETEVENT,
				SDL_EVENTMASK(SDL_MOUSEMOTION)) > 0)
			{
				while (SDL_PeepEvents(&new_event, 1, SDL_GETEVENT,
					SDL_EVENTMASK(SDL_MOUSEMOTION)) > 0) {};
				get_mouse_handler_base().mouse_motion_event(new_event.motion, browse_);
			}
			else
			{
				get_mouse_handler_base().mouse_motion_event(event.motion, browse_);
			}
			break;
		case SDL_MOUSEBUTTONDOWN:
		case SDL_MOUSEBUTTONUP:
			get_mouse_handler_base().mouse_press(event.button, browse_);
			post_mouse_press(event);
			if (get_mouse_handler_base().get_show_menu())
			{
				show_menu(get_display().get_theme().context_menu()->items(), event.button.x, event.button.y, true);
			}
			break;
		case SDL_ACTIVEEVENT:
			if (event.active.type == SDL_APPMOUSEFOCUS && event.active.gain == 0)
			{
				if (get_mouse_handler_base().is_dragging())
				{
					int x, y;
					Uint8 mouse_flags = SDL_GetMouseState(&x, &y);
					if ((mouse_flags & SDL_BUTTON_LEFT) == 0)
					{
						SDL_Event e;
						e.type = SDL_MOUSEBUTTONUP;
						e.button.state = SDL_RELEASED;
						e.button.button = SDL_BUTTON_LEFT;
						e.button.x = x;
						e.button.y = y;
						get_mouse_handler_base().mouse_press(event.button, browse_);
						post_mouse_press(event);
					}
				}
			}
			break;
		default:
			break;
	}
}


